package com.example.springboot.common.handler;

import com.example.springboot.common.utils.ListUtils;
import com.example.springboot.globalutils.BizException;
import com.example.springboot.globalutils.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    public GlobalExceptionHandler() {
    }

    @ExceptionHandler({BizException.class})
    public R<?> handleBizException(BizException e) {
        log.error("收到异常code: {}, msg: {}", new Object[]{e.getCode(), e.getMessage(), e});
        return R.fail(e.getCode(), e.getMessage());
    }

    @ExceptionHandler({NoHandlerFoundException.class})
    public R<?> handlerNoFoundException(Exception e) {
        log.error(e.getMessage(), e);
        return R.fail(404, "路径不存在，请检查路径是否正确");
    }

    @ExceptionHandler({Exception.class})
    public R<?> handleException(Exception e) {
        e.printStackTrace();
        log.error(e.getMessage(), e);
        return R.fail();
    }

    @ExceptionHandler({MissingServletRequestParameterException.class})
    public R<?> handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        log.error(e.getMessage(), e);
        return R.fail(1, "必要参数可能未传递");
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public R<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        String msg = ListUtils.join(bindingResult.getFieldErrors(), DefaultMessageSourceResolvable::getDefaultMessage, "；");
        return R.fail(1, msg);
    }

    @ExceptionHandler({HttpMessageNotReadableException.class})
    public R<?> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
        log.error(e.getMessage(), e);
        return R.fail(1, "参数解析错误，请检查参数是否正确");
    }
}

